package com.wbao.dianniu.ui;

import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.mobileim.IYWLoginService;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.YWLoginParam;
import com.alibaba.mobileim.channel.event.IWxCallback;
import com.alibaba.mobileim.utility.IMAutoLoginInfoStoreUtil;
import com.umeng.analytics.MobclickAgent;
import com.wbao.dianniu.customView.LoadingDialog;
import com.wbao.dianniu.customView.NoDoubleClickListener;
import com.wbao.dianniu.data.LoginResponse;
import com.wbao.dianniu.http.ErrorCode;
import com.wbao.dianniu.im.LoginSampleHelper;
import com.wbao.dianniu.im.NotificationInitSampleHelper;
import com.wbao.dianniu.im.UserProfileSampleHelper;
import com.wbao.dianniu.listener.IAuthCodeListener;
import com.wbao.dianniu.listener.ILoginListener;
import com.wbao.dianniu.listener.IRegisterListener;
import com.wbao.dianniu.logical.GlobalContext;
import com.wbao.dianniu.logical.SharedPreferencesUtils;
import com.wbao.dianniu.manager.LoginManager;
import com.wbao.dianniu.manager.RegisterManager;
import com.wbao.dianniu.utils.KeyboardHeightHandler;
import com.wbao.dianniu.utils.Notification;
import com.wbao.dianniu.utils.Utils;
import com.wbao.dianniu.R;

/**
 * 注册
 *
 * @author yejianjun
 */
public class RegisterActivity extends BaseActivity implements OnClickListener, IRegisterListener, IAuthCodeListener, ILoginListener {

    private final String TAG = RegisterActivity.class.getSimpleName();
    private Button registerBtn;
    private TextView authCodeTV;
    private EditText mobileEditText;
    private EditText authCdoeEditText;
    private EditText passwordEditText;
    private RegisterManager manager;
    private TextView agreementTV;
    private int count = 0;
    private LoginManager loginManager;
    private YWIMKit mIMKit;
    private Dialog pDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Utils.setTranslucentStatus(this, true);
            SystemBarTintManager tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintResource(R.color.title_bg);// 通知栏所需颜色
        }*/
        setContentLayout(R.layout.activity_register, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        initView();
        initData();
        if (0 == SharedPreferencesUtils.getKeyboardHeight(this)) {
            KeyboardHeightHandler handler = new KeyboardHeightHandler();
            handler.getKeyboardHeight(this);
        }

    }

    private void initData() {
        manager = new RegisterManager(this);
        manager.addListener(this);
        manager.addAuthListener(this);
        loginManager = new LoginManager(this);
        loginManager.addLoginListener(this);
    }

    private void initView() {
        setTitleName(R.string.register_register);
        registerBtn = (Button) findViewById(R.id.register_ok);
        authCodeTV = (TextView) findViewById(R.id.register_authCode);
        mobileEditText = (EditText) findViewById(R.id.input_Moblie);
        authCdoeEditText = (EditText) findViewById(R.id.forget_auth_code);
        passwordEditText = (EditText) findViewById(R.id.input_password);
//		authPasswordEditText = (EditText) findViewById(R.id.input_auth_password);
        agreementTV = (TextView) findViewById(R.id.user_agreement_tv);
        registerBtn.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                String mobile = mobileEditText.getText().toString().trim();
                String psd = passwordEditText.getText().toString().trim();
                String authCode = authCdoeEditText.getText().toString().trim();
                if (authMobile(mobile) && authPsd(psd, authCode)) {
                    if (count > 5) {
                        Notification.toast(RegisterActivity.this, getResources().getString(R.string.register_error_5_toast));
                        return;
                    }
                    manager.register(RegisterActivity.this, mobile, authCode, psd);
                }
            }
        });
        authCodeTV.setOnClickListener(this);
        agreementTV.setOnClickListener(this);
    }

    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            authCodeTV.setText(millisUntilFinished / 1000 + getResources().getString(R.string.auth_code_get_desc));
        }

        @Override
        public void onFinish() {
            authCodeTV.setEnabled(true);
            authCodeTV.setText(getResources().getString(R.string.register_get_auth_password));
        }
    };

    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        if(null != manager){
            manager.removeAuthListener(this);
            manager.removeListener(this);
        }
        if(null != loginManager){
            loginManager.removeLoginListener(this);
        }

    }

    ;

    @Override
    public void onClick(View v) {
        super.onClick(v);
        String mobile = mobileEditText.getText().toString().trim();
        String psd = passwordEditText.getText().toString().trim();
//		String authPsd = authPasswordEditText.getText().toString().trim();
        String authCode = authCdoeEditText.getText().toString().trim();
        switch (v.getId()) {
            case R.id.register_authCode:
                //获取验证码
                if (authMobile(mobile)) {
                    /** 每次获取验证码，清除错误累计 */
                    count = 0;
                    v.setEnabled(false);
                    authCodeTV.setBackgroundResource(R.drawable.get_code_unpress);
                    timer.start();
                    manager.getAuthCode(this, mobile);
                }
                break;
            case R.id.user_agreement_tv:
                Intent intent = new Intent();
                intent.setClass(this, UserAgreementActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    private boolean authPsd(String password, String authCode) {
        boolean ret = false;
        if (TextUtils.isEmpty(password)) {
            toastString(getResources().getString(R.string.login_error_3));
            return ret;
        } else if (password.length() < 6) {
            toastString(getResources().getString(R.string.register_error_2));
            return ret;
        }

//		if(TextUtils.isEmpty(authPassword)){
//			toastString(getResources().getString(R.string.register_error_3));
//			return ret;
//		}else if (!authPassword.equals(password)) {
//			toastString(getResources().getString(R.string.register_error_4));
//			return ret;
//		}
        if (TextUtils.isEmpty(authCode)) {
            toastString(getResources().getString(R.string.register_error_5));
            return ret;
        }

        return true;
    }

    private boolean authMobile(String mobile) {
        boolean ret = false;
        if (null == mobile) {
            toastString(getResources().getString(R.string.register_error_1));
            return ret;
        } else {
            boolean ismobile = mobile.matches("^(13|15|18|14|17)\\d{9}$");
            if (ismobile) {
                ret = true;
            } else {
                toastString(getResources().getString(R.string.login_error_1));
            }
            return ret;
        }
    }

    private void toastString(String message) {
        Notification.toast(RegisterActivity.this, message);
    }

    @Override
    public void onFailure(int errorCode, String errorMsg) {
        toastString(errorMsg == null ? "" : errorMsg);
        count++;
    }

    @Override
    public void onLoginFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        Notification.toast(this, errorMsg == null ? "" : errorMsg);
    }

    @Override
    public void onLoginSuccess(LoginResponse objdata) {
        Utils.saveLoginData(this,objdata);
        init(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), getResources().getString(R.string.app_key));
        //登录成功时，登录IM
        loginIM(objdata.getEnvironmentName() + objdata.getAccountInfo().getId(), Utils.Md5(passwordEditText.getText().toString().trim()));
    }

    private void init(String userId, String appKey) {
        final String hisUserId = IMAutoLoginInfoStoreUtil.getLoginUserId();
        if (!hisUserId.equals(userId) && !hisUserId.isEmpty()) {    // 两次登录用户不同 先调用登出命令再调用登录命令
            LoginSampleHelper.getInstance().loginOut_Sample();
        }
        //初始化imkit
        LoginSampleHelper.getInstance().initIMKit(userId, appKey);
        //自定义头像和昵称回调初始化(如果不需要自定义头像和昵称，则可以省去)
        UserProfileSampleHelper.initProfileCallback();
        //通知栏相关的初始化
        NotificationInitSampleHelper.init();
    }

    @Override
    public void onSuccess() {
//        toastString(getResources().getString(R.string.register_success));
        // 直接走登录流程～～～ 跳转到登录界面
        login();
    }

    @Override
    public void onAuthCodeFailure(int errorCode, String errorMsg) {
        if (null != pDialog && pDialog.isShowing()) {
            pDialog.dismiss();
        }
        toastString(errorMsg);
    }

    @Override
    public void onAuthCodeSuccess(Object objdata) {
    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    private void login() {
        showWaittingDialog();
        String username = mobileEditText.getText().toString().trim();
        String password = passwordEditText.getText().toString().trim();
        // 发送登录请求
        loginManager.Login(this, username, Utils.Md5(password), Utils.getDeviceId(this), null, null, Utils.getVersionName(RegisterActivity.this), null);
    }

    public void loginIM(String userId, String password) {
        if (null == LoginSampleHelper.getInstance().getIMKit()) {
            //初始化imik
            LoginSampleHelper.getInstance().initIMKit(userId, getResources().getString(R.string.app_key));
        }
        mIMKit = LoginSampleHelper.getInstance().getIMKit();
//        final String hisUserId = IMAutoLoginInfoStoreUtil.getLoginUserId();
//        if (!hisUserId.equals(userId) && !hisUserId.isEmpty()) {    // 两次登录用户不同 先调用登出命令再调用登录命令
//            LoginSampleHelper.getInstance().loginOut_Sample();
//        }
        //开始登录
        if (null == mIMKit) {
            Log.d(TAG, "im system init error ");
            return;
        }
//        Log.d(TAG, "开始登录IM：" + System.currentTimeMillis() + "");
        IYWLoginService loginService = mIMKit.getLoginService();
        YWLoginParam loginParam = YWLoginParam.createLoginParam(userId, password);
        loginService.login(loginParam, new IWxCallback() {

            @Override
            public void onSuccess(Object... arg0) {
//                Log.d(TAG, "登录成功IM：" + System.currentTimeMillis() + "");
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                // 保存自动登录配置信息
                saveConfigInfo();
                // 成功 界面跳转
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.setClass(RegisterActivity.this, MainActivity.class);
                startActivity(intent);
                RegisterActivity.this.finish();
            }

            @Override
            public void onProgress(int arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onError(int errCode, String description) {
                if (null != pDialog && pDialog.isShowing()) {
                    pDialog.dismiss();
                }
                //如果登录失败，errCode为错误码,description是错误的具体描述信息
                if (null != description) {
                    Notification.toast(RegisterActivity.this, description);
                } else {
                    Notification.toast(RegisterActivity.this, "【登录失败，错误码】：" + errCode);
                }

            }
        });
    }

    private void saveConfigInfo() {
        SharedPreferencesUtils.init(RegisterActivity.this);
        SharedPreferencesUtils.setUserName(mobileEditText.getText().toString());
//        SharedPreferencesUtils.setPassword(mPasswordText.getText().toString().trim());
        SharedPreferencesUtils.setPassword(Utils.Md5(passwordEditText.getText().toString().trim()));
        SharedPreferencesUtils.setAutoLoginStatus(true);
    }

    private void showWaittingDialog() {
        pDialog = LoadingDialog.createLoadingDialog(this, "正在登录...");
        pDialog.show();
    }


}
